package com.milo.concurrent.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * <p>
 *     RecursiveTask:又返回结果的任务
 * </p>
 * @author Milo Lee
 * @date 2022-04-15 15:02
 */
public class AccumulateTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;
    //累加起始编号
    private int start;
    //累加结束编号
    private int end;

    public AccumulateTask(int start,int end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //判断任务如果足够小,直接计算返回结果
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            System.out.println("直接计算结果");
            //直接计算结果
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //任务过大,需要切割,Recursive递归运算
            int middle = (start + end) / 2;
            //切割成两个子任务
            AccumulateTask task1 = new AccumulateTask(start, middle);
            AccumulateTask task2 = new AccumulateTask(middle + 1, end);
            //调用每个子任务的fork()方法切割子任务
            task1.fork();
            task2.fork();
            //等待子任务完成,调用每个子任务的join()方法合并执行结果
            Integer join1 = task1.join();
            Integer join2 = task2.join();
            //合并结果
            sum = join1 + join2;
        }
        return sum;
    }
}
